package com.jt.resource.controller;

import com.jt.resource.annotation.RequiredLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/*
实现文件上传服务
 */
@Slf4j
@RestController
@RefreshScope
@RequestMapping("/resource/")
public class ResourceController {
    @Value("${jt.resource.path}")
    private String path;
    @Value("${jt.resource.host}")
    private String host;

    @PreAuthorize("hasAuthority('sys:res:create')")
    @PostMapping("/upload/")
    @RequiredLog("文件上传")//扩展业务
    public String uploadfile(MultipartFile uploadFile) throws IOException {
        String dateDir = DateTimeFormatter.ofPattern("yyyy/MM/dd").format(LocalDate.now());
        File uploadFileDir = new File(path, dateDir);
        if(!uploadFileDir.exists())uploadFileDir.mkdirs();
        String originalFilename = uploadFile.getOriginalFilename();
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFilePrefix = UUID.randomUUID().toString();
        String newFileName=newFilePrefix+ext;
        File file = new File(uploadFileDir, newFileName);
        uploadFile.transferTo(file);
        String fileRealPath = host + dateDir+"/"+newFileName;
        log.debug(fileRealPath);
        return fileRealPath;
    }
}
